package com.cn.longdistancebusstation.personal;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.Result;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by mucheng on 2018/1/29.
 */

public class AlterTelephoneNumberActivity extends BaseActivity implements View.OnClickListener{
    private EditText mOldPhoneNumberEditText,mVerifyCodeEditText;
    private TextView tv_get_verify_code,phoneNumber;
    private Button bnt_commit;
    int i=60;
    private SharedPreferences mdata;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getTitleTextView().setText("修改手机号码");
        setContentView(R.layout.activity_alter_telephone_number);
        initView();
    }

    private void initView() {
        SharedPreferences sharedPreferences=getSharedPreferences("data",MODE_PRIVATE);
        String phoneNo=sharedPreferences.getString("telephone","");
        phoneNumber=(TextView)findViewById(R.id.current_phone_number);
        phoneNumber.setText(phoneNo);
        mOldPhoneNumberEditText=(EditText)findViewById(R.id.alter_et_phone_number);
        mOldPhoneNumberEditText.setOnClickListener(this);
        mVerifyCodeEditText=(EditText)findViewById(R.id.et_verification);
        mVerifyCodeEditText.setOnClickListener(this);
        bnt_commit=(Button)findViewById(R.id.btn_commit);
        bnt_commit.setOnClickListener(this);
        tv_get_verify_code=(TextView)findViewById(R.id.get_verification_code);
        tv_get_verify_code.setOnClickListener(this);
        //启动短信验证
        SMSSDK.initSDK(this,"23626de972632","7378e06fb9f365826f4d8f4001116cce");
        EventHandler eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        // 注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.btn_commit:
                checkVerificode();
                break;
            case R.id.get_verification_code:
                checkPhoneNumber();
                break;
        }
    }

    private void checkPhoneNumber() {
        showHud();
        String phonenum = mOldPhoneNumberEditText.getText().toString().trim();
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService service=retrofit.create(HttpService.class);
        Call<Result> call=service.checkPhoneIsExist(phonenum);
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                hideHud();
                Gson gson=new Gson();
                Result result=response.body();
                Boolean isSuccess=result.getHead().getSuccess();
                if(isSuccess){
                    verifycode();
                }else{
                    Toast.makeText(AlterTelephoneNumberActivity.this,result.getHead().getMsg(),Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                hideHud();
                Toast.makeText(AlterTelephoneNumberActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void verifycode() {
        String phoneNo=mOldPhoneNumberEditText.getText().toString().trim();
        if(phoneNo.equals("")){
            Toast.makeText(AlterTelephoneNumberActivity.this,"请输入手机号",Toast.LENGTH_SHORT).show();
        }else{
            // 2. 通过sdk发送短信验证
            SMSSDK.getVerificationCode("86", phoneNo);
            // 3. 把按钮变成不可点击，并且显示倒计时（正在获取）
            tv_get_verify_code.setClickable(false);
            tv_get_verify_code.setText("重新发送(" + i + ")");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (; i > 0; i--) {
                        handler.sendEmptyMessage(-9);
                        if (i <= 0) {
                            break;
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    handler.sendEmptyMessage(-8);
                }
            }).start();

        }
    }
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -9) {
                tv_get_verify_code.setText("重新发送(" + i + ")");
            } else if (msg.what == -8) {
                tv_get_verify_code.setText("获取验证码");
                tv_get_verify_code.setClickable(true);
                i = 60;
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("event", "event=" + event);
                Log.e("result", "result=" + result);
                System.out.println("SMSSDK.RESULT_COMPLETE="
                        + SMSSDK.RESULT_COMPLETE);
                if (result == SMSSDK.RESULT_COMPLETE)
                {
                    // 短信注册成功后，返回MainActivity,然后提示
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE)
                    {// 提交验证码成功
                        sure_alter_pNo();
//                       Toast.makeText(AlterTelephoneNumberActivity.this,"提交验证码成功",Toast.LENGTH_SHORT).show();
                    }
                    else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE)
                    {
                        Toast.makeText(getApplicationContext(), "验证码已经发送",
                                Toast.LENGTH_SHORT).show();
                        System.out.println("result_3");
                    } else {
                        System.out.println("result_4");
                        ((Throwable) data).printStackTrace();
                    }
                }
                else
                {
                    Throwable throwable = (Throwable) data;
                    String hint = "操作失败";
                    try {
                        JSONObject jsonObj = new JSONObject(throwable.getMessage());
                        hint = jsonObj.optString("detail");

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(getApplicationContext(), hint, Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    private void sure_alter_pNo() {
        SharedPreferences sharedPreferences=getSharedPreferences("data",MODE_PRIVATE);
        String old_telephone_number=sharedPreferences.getString("telephone","");
        final String new_telephone_verify_number=mVerifyCodeEditText.getText().toString().trim();
        final String new_telephoenNo=mOldPhoneNumberEditText.getText().toString().trim();
        if(new_telephoenNo.equals("")&&new_telephone_verify_number.equals("")){
            Toast.makeText(AlterTelephoneNumberActivity.this,"输入内容不能为空",Toast.LENGTH_SHORT).show();
        }else{
            showHud();
            Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
            HttpService service=retrofit.create(HttpService.class);
            Call<Result> call=service.editMobilePhone(old_telephone_number,new_telephoenNo);
            call.enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    hideHud();
                    Gson gson=new Gson();
                    Result result=response.body();
                    Boolean isSuccess=result.getHead().getSuccess();
                    if(isSuccess){
                        Toast.makeText(AlterTelephoneNumberActivity.this,"修改成功",Toast.LENGTH_SHORT).show();
                        SharedPreferences.Editor editor=getSharedPreferences("data",MODE_PRIVATE).edit();
                        editor.putString("telephoner",new_telephoenNo);
                        editor.apply();
                        finish();
                    }else{
                        Toast.makeText(AlterTelephoneNumberActivity.this,result.getHead().getMsg() ,Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    hideHud();
                    Toast.makeText(AlterTelephoneNumberActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        }
   }
    /**
     * 判断一个字符串的位数
     *
     * @param str
     * @param length
     * @return
     */
    public static boolean isMatchLength(String str, int length) {
        if (str.isEmpty()) {
            return false;
        } else {
            return str.length() == length ? true : false;
        }
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobileNums) {
		/*
		 * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
		 * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
		 * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
		 */
        String telRegex = "[1][358]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobileNums))
            return false;
        else
            return mobileNums.matches(telRegex);
    }
    /**
     * 判断验证码是否正确
     */
    private void checkVerificode() {
        String phonenum = mOldPhoneNumberEditText.getText().toString().trim();
        String code = mVerifyCodeEditText.getText().toString().trim();
        SMSSDK.submitVerificationCode("86", phonenum, code);
    }


}
